﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using DotNetNuke.Entities.Tabs;
using DotNetNuke.Entities.Modules;
using DotNetNuke.UI.Modules;
using DotNetNuke.UI.Skins;

namespace DesertedRoadStudios.BlogNetNuke.Utilities
{
    public class Posts
    {
        public static void ParseContent(PortalModuleBase module, string content)
        {
            HtmlControl contentPane = module.FindControl("ContentPane") as HtmlControl;
            if (contentPane != null)
            {
                int indexer = 0;
                int cntrlCnt = 0; // Need an unique identifier for multiple instances of the same module within the post

                string pattern = @"\[tabid/([0-9]+)/moduleid/([0-9]+)\]";
                Regex regex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);

                Match match = regex.Match(content);

                while (match.Success)
                {
                    Group tabID = match.Groups[1];
                    Group moduleID = match.Groups[2];

                    // Add a literal control for all text between metatags.
                    contentPane.Controls.Add(new LiteralControl(content.Substring(indexer, match.Index - indexer)));

                    // Add meta tag referenced control
                    contentPane.Controls.Add(RenderControlForTag(module, Convert.ToInt32(tabID.Value), Convert.ToInt32(moduleID.Value), cntrlCnt));
                    cntrlCnt++;

                    // Update indexer placement
                    indexer = match.Index + match.Length;

                    // Get next match
                    match = match.NextMatch();
                }

                if (indexer < content.Length)
                    contentPane.Controls.Add(new LiteralControl(content.Substring(indexer)));
            }
        }

        private static Control RenderControlForTag(PortalModuleBase module, int tabID, int moduleID, int cntrlCnt)
        {
            try
            {
                ModuleInfo moduleInfo = new ModuleController().GetModule(moduleID, tabID);
                string controlSrc = moduleInfo.ControlSrc;

                PortalModuleBase pmBase = (PortalModuleBase)module.LoadControl("~/" + controlSrc);
                pmBase.ModuleConfiguration = moduleInfo;
                pmBase.ID = "ctl" + String.Format("{0:00}", cntrlCnt);
                
                return pmBase;
            }
            catch (Exception exc)
            {
                throw new SystemException(exc.Message);
            }
        }
    }
}